package com.jprocms.module.cms.controller.admin.site;

import cn.hutool.core.collection.CollUtil;
import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.framework.common.util.collection.CollectionUtils;
import com.jpro.framework.excel.core.util.ExcelUtils;
import com.jpro.framework.security.core.LoginUser;
import com.jpro.framework.security.core.util.SecurityFrameworkUtils;
import com.jpro.module.system.api.permission.PermissionApi;
import com.jpro.module.system.api.permission.dto.SitePermissionRespDTO;
import com.jprocms.module.cms.controller.admin.site.vo.*;
import com.jprocms.module.cms.convert.site.SiteConvert;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.enums.EnumIntCommonStatus;
import com.jprocms.module.cms.service.site.SiteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.jpro.framework.common.pojo.CommonResult.error;
import static com.jpro.framework.common.pojo.CommonResult.success;
import static com.jprocms.module.cms.constant.CmsSysConstants.STATUS_OPEN;
import static com.jprocms.module.cms.enums.ErrorCodeConstants.COMMON_RPC_SYSTEM_ERROR;

@Tag(name = "管理后台 - 站点")
@RestController
@RequestMapping("/cms/site")
@Validated
public class SiteController {

    @Resource
    private SiteService siteService;

    @Resource
    private PermissionApi permissionApi;

    @PostMapping("/create")
    @Operation(summary = "创建站点")
    @PreAuthorize("@ss.hasPermission('cms:site:create')")
    public CommonResult<Long> createSite(@Valid @RequestBody SiteCreateReqVO createReqVO) throws IOException {
        return success(siteService.createSite(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新站点")
    @PreAuthorize("@ss.hasPermission('cms:site:update')")
    public CommonResult<Boolean> updateSite(@Valid @RequestBody SiteUpdateReqVO updateReqVO) {
        siteService.updateSite(updateReqVO);
        siteService.clearSiteCache(updateReqVO.getId());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除站点")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('cms:site:delete')")
    public CommonResult<Boolean> deleteSite(@RequestParam("id") Long id) {
        siteService.deleteSite(id);
        siteService.clearSiteCache(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得站点")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('cms:site:query')")
    public CommonResult<SiteRespVO> getSite(@RequestParam("id") Long id) {
        SiteDO site = siteService.getSite(id);
        return success(SiteConvert.INSTANCE.convert(site));
    }

    @GetMapping("/list")
    @Operation(summary = "获得站点列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('cms:site:query')")
    public CommonResult<List<SiteRespVO>> getSiteList(@RequestParam("ids") Collection<Long> ids) {
        List<SiteDO> list = siteService.getSiteList(ids);
        return success(SiteConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/list-all-simple")
    @Operation(summary = "获取精简信息列表")
    public CommonResult<List<SiteSimpleRespVO>> getSimpleSiteList() {
        // 获得站点列表，只要开启状态的
        SiteQueryReqVO reqVO = SiteQueryReqVO.builder().status(EnumIntCommonStatus.OPEN.getStatus()).build();
        List<SiteDO> list = siteService.getSiteList(reqVO);
        // 排序后，返回给前端
        list.sort(Comparator.comparing(SiteDO::getSort));
        return success(SiteConvert.INSTANCE.convertSimpleList(list));
    }

    @GetMapping("/getOwnerSiteList")
    @Operation(summary = "获取可管理站点列表")
    public CommonResult<List<OwnerSiteRespVO>> getOwnerSiteList() {
        // 获得站点列表，只要开启状态的
        SiteQueryReqVO reqVO = SiteQueryReqVO.builder().status(EnumIntCommonStatus.OPEN.getStatus()).build();
        List<SiteDO> list = siteService.getSiteList(reqVO);
        // 排序后，返回给前端
        list.sort(Comparator.comparing(SiteDO::getSort));
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        CommonResult<SitePermissionRespDTO> sitePermission = permissionApi.getSitePermission(loginUser.getId());
        if (sitePermission.isError()) {
            return error(COMMON_RPC_SYSTEM_ERROR);
        }
        SitePermissionRespDTO data = sitePermission.getData();
        if (data.getAll()) {
            return success(SiteConvert.INSTANCE.convertOwnerSiteList(list));
        } else {
            //过滤用户权限范围内站点
            Set<Long> ownerSiteIds = data.getSiteIds();
            List<Long> siteIds = CollectionUtils.convertList(list, SiteDO::getId);
            Collection<Long> intersectionSiteIds = CollUtil.intersection(siteIds, ownerSiteIds);
            List<SiteDO> filterSites = list.stream().filter(siteDO -> intersectionSiteIds.contains(siteDO.getId())).collect(Collectors.toList());
            return success(SiteConvert.INSTANCE.convertOwnerSiteList(filterSites));
        }
    }

    @GetMapping("/getAllowPushSiteList")
    @Operation(summary = "获取可推送站点列表")
    public CommonResult<List<SiteSimpleRespVO>> getAllowPushSiteList() {
        // 获得站点列表，只要开启状态的
        SiteQueryReqVO reqVO = SiteQueryReqVO.builder().status(EnumIntCommonStatus.OPEN.getStatus()).allowPush(STATUS_OPEN).build();
        List<SiteDO> list = siteService.getSiteList(reqVO);
        // 排序后，返回给前端
        list.sort(Comparator.comparing(SiteDO::getSort));
        return success(SiteConvert.INSTANCE.convertSimpleList(list));
    }

    @GetMapping("/getList")
    @Operation(summary = "获得站点树列表")
    public CommonResult<List<SiteRespVO>> getSiteList(@Valid SiteQueryReqVO pageVO) {
        List<SiteDO> list = siteService.getSiteList(pageVO);
        list.sort(Comparator.comparing(SiteDO::getSort));
        return success(SiteConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出站点 Excel")
    @PreAuthorize("@ss.hasPermission('cms:site:export')")

    public void exportSiteExcel(@Valid SiteQueryReqVO exportReqVO,
                                HttpServletResponse response) throws IOException {
        List<SiteDO> list = siteService.getSiteList(exportReqVO);
        // 导出 Excel
        List<SiteExcelVO> datas = SiteConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "站点.xls", "数据", SiteExcelVO.class, datas);
    }

}
